﻿using System.Text.Json;
using System.Text.RegularExpressions;
using System.Globalization;

namespace TowerCraneMonitorClient.NetClient
{
    public static class JsonExtentions
    {
        /// <summary>
        /// 匹配 Web 风格字符串中 "\uXXXX"
        /// </summary>
        static readonly Regex reUnicode = new Regex(@"\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);

        /// <summary>
        /// 转换 Web 字符串中 \uXXXX 为 Unicode 字符
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        static string ToUnicode(string s)
        {
            return reUnicode.Replace(s, tryParse);

            string tryParse(Match m)
            {
                var c = (char)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                return c.ToString();
            }
        }

        /// <summary>
        /// 对象序列化至 Json 字符串
        /// </summary>
        /// <typeparam name="T">欲序列化的对象类型</typeparam>
        /// <param name="o">欲序列化对象</param>
        /// <param name="indented">输出是否缩进格式</param>
        /// <returns>json 字符串</returns>
        public static Json ToJson<T>(this T o, bool indented = true)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = indented, // 是否缩进格式
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase // 自动驼峰命名
            };
            var webString = JsonSerializer.Serialize(o, options);
            return new Json(ToUnicode(webString));
        }
    }
}
